package com.quanz.ckgl.tools;

import java.util.Collection;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 
 * @author James Quan
 * @version 2015年10月4日 下午4:23:08
 */
public class AuthHelper {
	/**
	 * 匿名用户信息
	 */
	public static String ANONYMOUS_USER_ACCOUNT = "anonymous";
	public static String ANONYMOUS_USER_NAME = "匿名用户";
	/**
	 * 角色身份所使用的前缀
	 */
	private static String rolePrefix = "ROLE_";

	/**
	 * 返回当前使用者的{@link Authentication}对象
	 * 
	 * @return
	 */
	public static Authentication getCurrentAuthentication() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		return authentication;
	}

	/**
	 * 返回当前使用者的帐号
	 * 
	 * @return
	 */
	public static String getCurrentUser() {
		Authentication authentication = getCurrentAuthentication();
		if (authentication == null) {
			return AuthHelper.ANONYMOUS_USER_ACCOUNT;
		}
		if (authentication.getPrincipal() == null) {
			return AuthHelper.ANONYMOUS_USER_ACCOUNT;
		}
		String principal;
		if (authentication.getPrincipal() instanceof UserDetails) {
			principal = ((UserDetails) authentication.getPrincipal()).getUsername();
		} else {
			principal = authentication.getPrincipal().toString();
		}
		return principal;
	}

	/**
	 * 返回身份判定时角色所使用的前缀
	 * 
	 * @return
	 */
	public static String getRolePrefix() {
		return rolePrefix;
	}

	/**
	 * 设置身份判定时角色所使用的前缀
	 * 
	 * @param rolePrefix
	 */
	public static void setRolePrefix(String rolePrefix) {
		AuthHelper.rolePrefix = rolePrefix;
	}

	/**
	 * 判断当前登录用户是否具有指定的角色
	 * 
	 * @return 具有则返回<code>true</code>，否则返回<code>false</code>
	 */
	public static boolean isUserHasRole(String role) {
		Authentication authentication = getCurrentAuthentication();
		if (authentication == null) {
			return false;
		}
		Collection<? extends GrantedAuthority> authorities = authentication
				.getAuthorities();
		if (authorities.isEmpty()) {
			return false;
		}
		String roleName = rolePrefix + role;
		for (GrantedAuthority authority : authorities) {
			if (roleName.equals(authority.getAuthority())) {
				return true;
			}
		}
		return false;
	}

}
